package com.example.authorization_server.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.util.UUID;

/**
 * @author 罗俊华
 * @date 2022/3/14 - 12:06 下午
 */
@Slf4j
@Service
public class RedisAuthorizationCodeServices implements AuthorizationCodeServices {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String createAuthorizationCode(OAuth2Authentication authentication) {

        String key = UUID.randomUUID().toString().substring(0, 5);

        try {
            String val = new ObjectMapper().writeValueAsString(authentication);

            stringRedisTemplate.opsForValue().set(key,val);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        return key;
    }

    @Override
    public OAuth2Authentication consumeAuthorizationCode(String code) throws InvalidGrantException {


        String val = stringRedisTemplate.opsForValue().get(code);

        if(StringUtils.hasLength(val)){

            // TODO json反序列化有问题，因为 OAuth2Authentication 对象没有无参构造器

            OAuth2Authentication result = new Gson().fromJson(val, OAuth2Authentication.class);


            stringRedisTemplate.delete(code);

            return result;

        }
        return null;
    }
}
